 package com.web.service;

 import com.alibaba.fastjson.JSON;
 import com.auth0.jwt.JWT;
 import com.auth0.jwt.algorithms.Algorithm;
 import com.web.entity.UserInfo;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Service;

 import java.io.UnsupportedEncodingException;
 import java.util.Date;

 @Service
public class AuthenticationService {
     @Autowired
     public StringRedisTemplate redisTemplate;

     // 过期时间10天
    private static final long EXPIRE_TIME = 60*60*1000*24*10;
    //private static final long EXPIRE_TIME = 10*1000;
    public String getToken(UserInfo person) {
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        String token = "";
        try {
            token = JWT.create()
                    .withAudience(person.getUserId())// 将 user id 保存到 token 里面
                    .withExpiresAt(date)  // 失效时间
                    .sign(Algorithm.HMAC256(person.getUserId()));   // 以 用户id 作为 token 的密钥
        } catch (UnsupportedEncodingException ignore) {
            ignore.printStackTrace();
        }
        redisTemplate.opsForValue().set("TOKEN:"+person.getUserId(),token);
        return token;
    }
}